package com.zhxq.ai.controller;

import com.zhxq.ai.domain.vo.MessageVo;
import com.zhxq.ai.repository.ChatHistoryRepository;
import com.zhxq.common.core.domain.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/ai/history")
@Tag(name = "会话历史")
public class ChatHistoryController {

    @Resource
    private ChatHistoryRepository inMemoryChatHistoryRepository;

    @Resource(name = "simpleChatMemoryConfig")
    private ChatMemory simpleChatMemory;

    /**
     * 根据用户和会话类型查询会话历史列表
     * @param chatType 业务类型，如：chat,service,pdf
     * @return chatId列表
     */
    @Operation(summary = "根据用户和会话类型查询会话历史列表")
    @GetMapping("/chat/{chatType}")
    public AjaxResult getChatIds(@PathVariable("chatType") String chatType) {
        return AjaxResult.success(inMemoryChatHistoryRepository.getChatIds(chatType));
    }

    /**
     * 根据chatId查询会话历史
     * @param chatId 会话id
     * @return 指定会话的历史消息
     */
    @Operation(summary = "根据chatId查询会话历史")
    @GetMapping("/message/{chatId}")
    public AjaxResult getChatHistory(@PathVariable("chatId") String chatId) {
        List<Message> messages = simpleChatMemory.get(chatId, Integer.MAX_VALUE);
        if(messages == null) {
            return AjaxResult.success(List.of());
        }
        return AjaxResult.success(messages.stream().map(MessageVo::new).toList());
    }

}
